package com.baozun.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.Test;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

/**
 * 
 * @Title:
 * @Company:宝尊电子商务有限公司
 * @Author:万世极缘
 * @Since:2015-1-12
 * @Copyright:Copyright (c) 2015
 * @ModifyDate:2015-1-12
 * @Version:1.1.0
 */
public class ModelAndViewUtil {

    private Map<String, Object> model = new HashMap<String, Object>();
    private ModelAndViewUtil util;

    /**
     * 
     * @param model
     * @param obj
     * @return
     */
    public ModelAndViewUtil setModel(String key, Object value) {
        if (util == null) {
            util = new ModelAndViewUtil();
        }
        model.put(key, value);
        return this;
    }

    public ModelAndView toUrl(String url) {
//        Set<Entry<String, Object>> set = model.entrySet();
//        Iterator<Entry<String, Object>> ite = set.iterator();
//        while(ite.hasNext()){
//            Entry<String, Object> entry = ite.next();
//            System.out.println("得到key为："+entry.getKey());
//            System.out.println("得到value为:"+entry.getValue());
//        }
        return new ModelAndView(url, model);
    }

    public ModelAndViewUtil setModel(Map<String, Object> model2) {
        model.putAll(model2);
        return this;
    }

    public ModelAndView toRedirectUrl(String url) {
        return new ModelAndView(new RedirectView(url), model);
    }

    @Test
    public void show() {
        ModelAndViewUtil util1 = new ModelAndViewUtil().setModel("1","1").setModel("2","2");
        ModelAndViewUtil util2 = new ModelAndViewUtil().setModel("a","a").setModel("b","b");
        
        Map<String, Object> model = util1.model;
        Set<Entry<String, Object>> set = model.entrySet();
        Iterator<Entry<String, Object>> ite = set.iterator();
        while (ite.hasNext()) {
            Entry<String, Object> entry = ite.next();
            System.out.print(entry.getKey() + ":\t");
            System.out.print(entry.getValue() + "\n");
        }
        System.out.println("#######################");
        model = util2.model;
        set = model.entrySet();
        ite = set.iterator();
        while (ite.hasNext()) {
            Entry<String, Object> entry = ite.next();
            System.out.print(entry.getKey() + ":\t");
            System.out.print(entry.getValue() + "\n");
        }
    }
}
